import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserProfile, getUserDetailed } from '@/api/user'
import { login } from '@/api/user'
import { Message } from 'element-ui'
import { resetRouter } from '@/router'

export default {
  // 放入核心配置项
  namespaced: true, // 子模块开启命名空间
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updataToken(state, token) {
      state.token = token
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    upUserInfo(state, info) {
      state.userInfo = info
    },
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async getinitToken(context, loginForm) {
      const res = await login(loginForm)
      // console.log(res, 'res')
      if (res.code !== 10000) return Message.error(res.message)
      Message.success(res.message)
      context.commit('updataToken', res.data)
    },
    async getUserInfo(context) {
      const res = await getUserProfile()
      console.log(res, 'res')
      context.commit('upUserInfo', res.data)

      const avatar = await getUserDetailed(res.data.userId)
      console.log(avatar, 'avatar')
      context.commit('upUserInfo', { ...res.data, ...avatar.data })

      return res.data.roles.menus
    },
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
      // 重置路由
      resetRouter()
    }
  }
}
